package com.wptai.disconf.client.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.ho.yaml.Yaml;

import java.io.InputStream;
import java.util.*;

@Slf4j
public class YamlUtil {

    /**
     * key:文件名索引
     * value:配置文件内容
     */
    private static Map<String, LinkedHashMap<String,Object>> ymls = new HashMap();

    /**
     * string:当前线程需要查询的文件名
     */
    private static ThreadLocal<String> nowFileName = new ThreadLocal();


    /**
     * 递归查询yml下的值
     * @param fileName
     * @param key
     * @param map
     */
    public static void recursionYml(String fileName, String key, Map map){
        //默认为空
        String sKey = StringUtils.defaultString(key,"");
        map.forEach((k,v) -> {
            //拼key
            String lastKey  = "".equals(sKey) ? String.valueOf(k) : (sKey+'.'+k);
            if(v instanceof Map){
                //继续递归
                recursionYml(fileName, lastKey,(Map)v);
            }else{
                //转存
                ymls.get(fileName).put(lastKey,v);
            }
        });

    }

    /**
     * 加载配置文件
     * @param fileName
     */
    public static void load(final String fileName) {
        log.info(" loadYml file =" + fileName);
        nowFileName.set(fileName);
        if(ymls.containsKey(fileName)){
            log.info(" ymls has exits  file =" + fileName);
            return;
        }
        log.info("start load file =" + fileName);
        ymls.put(fileName, new LinkedHashMap<>());
        InputStream is = YamlUtil.class.getResourceAsStream("/" + fileName);
        Yaml.loadStream(is).iterator().forEachRemaining(e -> {
            recursionYml(fileName, null, (Map) e);
        });
    }

    /**
     * 获取yml的key的值
     * @param key
     * @return
     * @throws Exception
     */
    public static Object getValue(String key) {
        // 将配置文件进行复制
        Map<String,Object> ymlInfo = (Map)ymls.get(nowFileName.get()).clone();
        if(!ymlInfo.containsKey(key)){
            log.error("oh GA-GA!竟然找不到");
            throw new RuntimeException("不可能到这里的...");
        }
        return ymlInfo.get(key);
    }

    public static Object getValue(String fileName, String key){
        // 首先加载配置文件
        load(fileName);
        return getValue(key);
    }

}
